/*
 * 视频侦测
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20220419
 * Time: 11:05 
*/
layui.extend({
  setter: 'config' //配置模块
  ,faceapi: 'lib/extend/faceapi' //人脸识别
  // ,materialize: 'lib/extend/materialize' 
}).define(['setter','jquery','faceapi'],function(exports){ //提示：模块也可以依赖其它模块，

var setter = layui.setter;
var $ = layui.jquery;
var descriptors = { desc1: null, desc2: null };
const SSD_MOBILENETV1 = 'ssd_mobilenetv1';
const TINY_FACE_DETECTOR = 'tiny_face_detector';
let selectedFaceDetector = SSD_MOBILENETV1;
var forwardTimes = [];
var check=true;
var img;
var imgi=0;

var facevideo = {
    render:function($this, options){
        var divID,listplay;
        var that=this,models,timer,video,trackBox,canvasImg,matchedScore,mediaSize,threshold;

        this.divID = $this;
        this.threshold =options.threshold ? options.threshold :  0.5;
        this.models = options.models ? options.models : '/static/lay/lib/models';
        this.matchedScore = options.matchedscore ? options.matchedscore : 0.5;
        this.mediaSize  = options.mediasize ? options.mediasize : { width:640, height:360 };
        this.imgUrl = options.imgurl ? options.imgurl : '/static/lay/lib/models/ceshi2.png';
        this.videoUrl = options.videourl ? options.videourl : ['/static/lay/lib/models/bbt.mp4'];
        this.timer = options.timer ? options.timer :3000;
        img = options.imgnumber ? options.imgnumber : 12;

        var withFaceLandmarks = options.landmarks ? options.landmarks : false;
        var withBoxes = options.boxes ? options.boxes : true;

        that.resize();

        this.video = document.querySelector('#video');
        this.trackBox = document.querySelector('#trackBox');
        this.canvasImg = document.querySelector('#canvasImg');
        this.playvideo = document.querySelector('#playvideo');
        this.pausevideo = document.querySelector('#pausevideo');
        this.startcheck = document.querySelector('#startcheck');
        this.stopcheck = document.querySelector('#stopcheck');

        $("input[name='hidesound']").change(async function(){ 
             document.querySelector('#video').muted=$("input[name='hidesound']:checked").val();
        })

        $("input[name='loopplay']").change(async function(){
             document.querySelector('#video').loop=$("input[name='loopplay']:checked").val();
             if($("input[name='loopplay']:checked").val()){
                  document.querySelector('#video').play();  
             }
             
        })

        $("input[name='loopplaylist']").change(async function(){ 
             if($("input[name='loopplaylist']:checked").val()){
                listplay=setInterval(function(){ 
                    facevideo.autoplaylist($('#videoid').val());
                    console.log($('#videoid').val());
                 }, 5000);
             }else{
                clearInterval(listplay);
             };  
        })

        $("input[name='auto']").change(async function(){ 
            if($("input[name='auto']:checked").val()){
                document.querySelector('#video').autoplay=$("input[name='auto']:checked").val();
                document.querySelector('#video').play();
                
             }else{
                document.querySelector('#playvideo').className='';
                document.querySelector('#video').pause();
             };
        })

        $("input[name='checkfaceimg']").change(async function(){ 
             if($("input[name='checkfaceimg']:checked").val()){
                $('#checkimg').show();
             }else{
                $('#checkimg').hide();
             };
        })
        
        Promise.all([
            faceapi.nets.ssdMobilenetv1.loadFromUri(this.models),
            faceapi.nets.tinyFaceDetector.loadFromUri(this.models)
        ]).then(that.run());     

        that.bindEvents();
 
    },
    /*设置相关容器*/
    resize:function() {
        var content='';
        //动态创建css
        var style = document.createElement('style');
        style.type = 'text/css';
        style.rel = 'stylesheet';
        var code ='button{margin: 0 5px;display: inline-block;vertical-align: middle;height: 38px;line-height: 38px;border: 1px solid transparent;padding: 0 18px;background-color: #1e9fff;color: #fff;white-space: nowrap;text-align: center;font-size: 14px;border-radius: 2px;cursor: pointer;}';
            code +='button:hover {background-color: #4CAF50; color: white;}';
            code +='.active{background-color: #4CAF50; color: white;}';
            code +='input[type="text"]{padding:0 10px; width:80px; height: 38px;line-height: 38px;border: 1px solid #b5b5b5;background-color: #fff;color: rgba(0,0,0,.85);border-radius: 2px; margin:0px 30px 0px 0px;}';
            code +='input[type="checkbox"]{width: 18px; height: 18px; padding:2px; background-color: #fff; border: 1px solid #c9c9c9; border-radius: 2px; color: #fff; text-align: center; line-height: 15px; -webkit-appearance: none; appearance: none; outline: none; margin:0 10px 0 5px; cursor: pointer;}';
            code +='input[type="checkbox"]:hover{ border: 1px solid #43adea;}';
            code +='input[type="checkbox"]:checked{color: #fff; background-color: #43adea; border: 1px solid #43adea;}';
            code +='input[type="checkbox"]:after{content: "√";}';
            code +='#trackBox, .trackBox {position: absolute;}';
            code += this.divID+'{width:100%; height:100%;position: absolute; left:50%;right: 50%;transform: translateX(-50%);}';
            code +='#leftdiv{font-size:16px;float:left; width:calc(50% - 40px); padding:10px 20px;position: absolute;top: 0;left: 0;}';
            code +='#rightdiv{font-size:16px;float:right; width:calc(50% - 40px); padding:10px 0px;position: absolute;top: 0;right: 0;}';
            code +='.title{width:100%;height:45px; line-height:45px;font-size:16px;font-weight:bold;position: absolute;}';
            code +='#video{position: absolute; }';
            code +='.list a li{float:left; width:25px;height:25px; margin:7px; line-height:25px;text-align:center; border:1px solid #1e9fff; }';
            code +='.list a li:hover{background-color: #4CAF50; color:#fff;}';
            
            code +='select{margin: 0 5px;display: inline-block;vertical-align: middle;height: 38px;line-height: 38px;border: 1px solid #1e9fff ;padding: 0 18px;white-space: nowrap;text-align: center;font-size: 14px;border-radius: 2px;cursor: pointer;}';
        
        try{
        style .appendChild(document.createTextNode(code));//for Chrome Firefox Opera Safari
        }catch(ex){
        style.styleSheet.cssText = code;//for IE
        }
        var head = document.getElementsByTagName('head')[0];//for IE
        head.appendChild(style);

        const wraper = document.querySelector(this.divID);
        
        const leftdiv=document.createElement("div");
        leftdiv.setAttribute("id", 'leftdiv');
        // leftdiv.setAttribute("style", '');
        content ='<div class="title">视频人脸甄别</div>';

        content +='<div style="position: absolute;top:55px;left:25%;right: 25%;transform: translateX(-30%);">';
        content +='<video id="video" muted loop playsinline width='+this.mediaSize.width+' height='+this.mediaSize.height+'></video>';
        content +='<canvas id="trackBox"></canvas>';
        content +='</div>';

        content +='<div style="width:100%;height:45px;position: absolute;top:'+(this.mediaSize.height+75)+'px">';
        content +='<button id="playvideo">播放</button>';
        content +='<button id="pausevideo">暂停</button>';
        content +='<button id="startcheck">检测</button>';
        content +='<button id="stopcheck">停止</button>';
        content +='<label>选择人脸检测器</label>';
        content +='<select id="selectFaceDetector">';
        content +='<option value="ssd_mobilenetv1">SSD Mobilenet V1</option>';
        content +='<option value="tiny_face_detector" selected>Tiny Face Detector</option>';
        content +='</select>';
        content +='</div>';

        content +='<div style="width:100%;height:45px;line-height:45px;position: absolute;top:'+(this.mediaSize.height+120)+'px">';
        content +='<label for="withFaceLandmarks" >检测人脸特征点</label>';
        content +='<input type="checkbox" name="withFaceLandmarks" value="true"/>';
        content +='<label for="hideBoundingBoxes" >隐藏边界框</label>';
        content +='<input type="checkbox" name="hideBoundingBoxes" value="true"/>';
        content +='<label for="hidesound" style="margin:0px 0px 0px 10px;">静音</label>';
        content +='<input type="checkbox" name="hidesound" value="true" checked/>';
        content +='<label for="loopplay" style="margin:0px 0px 0px 10px;">循环播放</label>';
        content +='<input type="checkbox" name="loopplay" value="true" checked/>';
        content +='<label for="auto" style="margin:0px 0px 0px 10px;">自动播放</label>';
        content +='<input type="checkbox" name="auto" value="true" />';
        content +='<label for="loopplaylist" style="margin:0px 0px 0px 10px;">列表播放</label>';
        content +='<input type="checkbox" name="loopplaylist" value="true" />';      
        content +='</div>';

        content +='<div style="position: absolute;top:'+(this.mediaSize.height+165)+'px">';
        content +='<span id="fps_meter" style="margin:0px 0px 0 0px;">';
        content +='<label for="time">时间：</label>';
        content +='<input disabled value="-" id="time" type="text" class="text">';
        content +='<label for="fps">帧数：</label>';
        content +='<input disabled value="-" id="fps" type="text" class="text">';
        content +='</span>';
        content +='</div>';
        
        content +='<div style="position: absolute;top:'+(this.mediaSize.height+210)+'px">';
        content +='<div id="ssd_mobilenetv1_controls" >';
        content +='<label for="minConfidence">最小识别值：</label>';
        content +='<input disabled value="0.5" id="minConfidence" type="text" >';
        content +='<button id="DecreaseMin"> <i class="material-icons left">-</i> </button>';
        content +='<button id="IncreaseMin"> <i class="material-icons left">+</i> </button>';
        content +='</div>';
        content +='<div id="tiny_face_detector_controls">';
        content +='<label>输入大小：</label>';
        content +='<select id="inputSize">';
        content +='<option value="" disabled selected>Input Size:</option>';
        content +='<option value="160">160 x 160</option>';
        content +='<option value="224">224 x 224</option>';
        content +='<option value="320">320 x 320</option>';
        content +='<option value="416" selected>416 x 416</option>';
        content +='<option value="512">512 x 512</option>';
        content +='<option value="608">608 x 608</option>';
        content +='</select>';
        content +='<label for="scoreThreshold">分数阈值：</label>';
        content +='<input disabled value="0.5" id="scoreThreshold" type="text">';
        content +='<button id="DecreaseScore"><i class="material-icons left">-</i></button>';
        content +='<button id="IncreaseScore"><i class="material-icons left">+</i></button>';
        content +='</div>';
        content +='</div>';

        content +='<div style="position: absolute;top:'+(this.mediaSize.height+255)+'px; line-height:45px; height:45px;">';
        content +='<label style="float:left;">播放列表：</label>';
        content +='<input disabled id="videoid" type="hidden">';
        content +='<span class="list">';
        this.videoUrl.forEach(function(value,index){
            content +='<a href="#" onclick="layui.facevideo.playlist('+index+')" ><li id=list'+(index+1);
            if(index==0){
            content += ' class="active" ';    
            }
            content +=' >'+(index+1)+'</li></a>';
        })
        content +='</span>';
        content +='</div>';

        content +='<div style="width:100%;height:45px;line-height:45px;position: absolute;top:'+(this.mediaSize.height+290)+'px">';
        content +='<label>检测操作：</label>';
        content +='<label for="getfaceimg">获取人脸图片</label>';
        content +='<input type="checkbox" name="getfaceimg" value="true" />';
        content +='<label for="checkfaceimg" style="margin:0px 0px 0px 20px;">对比人脸图片</label>';
        content +='<input type="checkbox" name="checkfaceimg" value="true" />'; 
        content +='</div>';

        content +='<div id="checkimg" style="width:100%;position: absolute;top:'+(this.mediaSize.height+335)+'px; display:none;">';
        content +='<div>';
        content +='<label for="DistanceTime">时间间距(ms)：</label>';
        content +='<input disabled value="3000" id="DistanceTime" type="text">';
        content +='<button id="Decreasetime"><i class="material-icons left">-</i></button>';
        content +='<button id="Increasetime"><i class="material-icons left">+</i></button>';
        content +='<label for="DistanceThreshold">欧式距离：</label>';
        content +='<input disabled value="0.5" id="DistanceThreshold" type="text">';
        content +='<button id="Decreasethreshold"><i class="material-icons left">-</i></button>';
        content +='<button id="Increasethreshold"><i class="material-icons left">+</i></button>';
        content +='</div>';
        content +='<label>上传图片：</label>';
        content +='<input type="file" onchange="layui.facevideo.preview(this,true)" />';
        content +='<div style="margin-top:10px;">';
        content +='<img id="img" style="height:80px;">';
        content +='</div>';
        content +='</div>';

        leftdiv.innerHTML=content;
        wraper.appendChild(leftdiv);

        const rightdiv=document.createElement("div");
        rightdiv.setAttribute("id", 'rightdiv');
        content ='<div class="title">视频显示</div>';
        content +='<div style="position: absolute;top:55px;">';
        content +='<canvas id="canvasImg" style=" width:'+this.mediaSize.width+'px; height:'+this.mediaSize.height+'px; border:1px solid #e2e2e2;"></canvas>';
        content +='</div>';
        content +='<div class="title" style="position: absolute;top:'+(this.mediaSize.height+65)+'px">人脸图片</div>';
        content +='<div style="width:'+this.mediaSize.width+';height:45px;position: absolute;top:'+(this.mediaSize.height+105)+'px">';
        while (imgi<img){
            content +='<img id="img'+imgi+'" width="106px" height="80px">';
            imgi++;
        }
        content +='</div>';
        content +='<div class="title" style="position: absolute;top:'+(this.mediaSize.height+265)+'px">结果显示</div>';
        content +='<div id="imgdiv" style="width:'+this.mediaSize.width+';position: absolute;top:'+(this.mediaSize.height+305)+'px"></div>';
        rightdiv.innerHTML=content;
        wraper.appendChild(rightdiv);

    },
    
    /** @name 播放视频检测 */
    async startVideo(videoEl) {
      if(!check){ 
        this.trackBox.setAttribute('height', 0);
        return false;
      }
      if(!videoEl.currentTime || videoEl.paused || videoEl.ended ) { return setTimeout(() => facevideo.startVideo(videoEl));} 
      
      const options = facevideo.getFaceDetectorOptions();
      const drawconfig = facevideo.getCheckbox();
      const ts = Date.now()
      let task = faceapi.detectAllFaces(videoEl, options)
      task = drawconfig['withFaceLandmarks'] ? task.withFaceLandmarks() : task
      const results = await task
      this.updateTimeStats(Date.now() - ts)
      const canvas = this.trackBox
      const displaySize = { width: videoEl.width, height: videoEl.height };
      const dims = faceapi.matchDimensions(canvas, displaySize, true);
      const resizedResults = faceapi.resizeResults(results, dims);
      if (!drawconfig['drawBoxes']) {
        faceapi.draw.drawDetections(canvas, resizedResults)
      }
      if (drawconfig['withFaceLandmarks']) {
        faceapi.draw.drawFaceLandmarks(canvas, resizedResults)
      }

      if(resizedResults.length>0){
        this.canvasImg.width=this.mediaSize.width;
        this.canvasImg.height=this.mediaSize.height;
        this.canvasImg.getContext('2d').drawImage(videoEl, 0, 0, this.mediaSize.width, this.mediaSize.height);
        if($("input[name='getfaceimg']:checked").val()){
            //获取人脸照片
            if(imgi>img-1){ imgi=0 }
            document.getElementById('img'+imgi).src = this.canvasImg.toDataURL('image/png');
            imgi++;
        }

      }
      setTimeout(() => facevideo.startVideo(videoEl));
    },

    /** @name 对比检测 */
    async checkVideo(videoEl) {
      if(!check){ 
        return false;
      }
      if(!videoEl.currentTime || videoEl.paused || videoEl.ended ) { return setTimeout(() => facevideo.checkVideo(videoEl),this.timer);} 
      
      const options = facevideo.getFaceDetectorOptions();
      const drawconfig = facevideo.getCheckbox();
      let task = faceapi.detectAllFaces(videoEl, options)
      if($("input[name='checkfaceimg']:checked").val() && document.getElementById('img').src !=''){
      // if(resizedResults.length>0){
        var canvas = document.createElement('canvas');
        canvas.width=this.mediaSize.width;
        canvas.height=this.mediaSize.height;
        var image = document.createElement('img');
        image.setAttribute("id", "imgs");
        canvas.getContext('2d').drawImage(videoEl, 0, 0, this.mediaSize.width,  this.mediaSize.height);
        image.src = canvas.toDataURL('image/png');
            //比对人脸
                await faceapi.nets.faceRecognitionNet.loadFromUri(this.models);
                    descriptors[`desc1`] = await faceapi.computeFaceDescriptor(document.getElementById('img'));
                    descriptors[`desc2`] = await faceapi.computeFaceDescriptor(image);
                    facevideo.updateResult(image);
            }

      setTimeout(() => facevideo.checkVideo(videoEl),this.timer);
    },

    /** @name 获取数据模型 */
    getFaceDetectorOptions() {
        return selectedFaceDetector = ($('#selectFaceDetector').children('option:selected').val() == SSD_MOBILENETV1) 
        ? new faceapi.SsdMobilenetv1Options({ minConfidence:parseFloat($('#minConfidence').val()) }) 
        : new faceapi.TinyFaceDetectorOptions({ inputSize:parseInt($('#inputSize').children('option:selected').val()), scoreThreshold:parseFloat($('#scoreThreshold').val()) })
    },
    /** @name 切换数据模型 */
    changeFaceDetector(models) {
        
        $('#selectFaceDetector').change(async function(){ 
           ['#ssd_mobilenetv1_controls', '#tiny_face_detector_controls'].forEach(id => { $(id).hide(); });
           selectedFaceDetector=$(this).children('option:selected').val();
           $('#'+selectedFaceDetector+'_controls').show();
           if (selectedFaceDetector == SSD_MOBILENETV1) {
               facevideo.MinConfidence();
            }else if (selectedFaceDetector == TINY_FACE_DETECTOR) {  
               facevideo.ScoreThreshold();
            }
        })
        
    },
    /** @name 调整阙值 */
    ScoreThreshold() {
        scoreThreshold=$('#scoreThreshold').val();
        $('#IncreaseScore').click(function(){ 
        scoreThreshold = Math.min(faceapi.utils.round(parseFloat(scoreThreshold) + 0.1), 0.99)
        $('#scoreThreshold').val(scoreThreshold);
        });

        $('#DecreaseScore').click(function(){ 
        scoreThreshold = Math.max(faceapi.utils.round(parseFloat(scoreThreshold) - 0.1), 0.1);
        $('#scoreThreshold').val(scoreThreshold);
        });
    },
    /** @name 调整阙值 */
    MinConfidence() {
        minConfidence=$('#minConfidence').val();
        $('#IncreaseMin').click(function(){ 
            minConfidence = Math.min(faceapi.utils.round(parseFloat(minConfidence) + 0.1), 0.99)
            $('#minConfidence').val(minConfidence)
        });

        $('#DecreaseMin').click(function(){
        minConfidence = Math.max(faceapi.utils.round(parseFloat(minConfidence) - 0.1), 0.1)
        $('#minConfidence').val(minConfidence)
        });
    },
    /** @name 调整欧式阙值 */
    DistanceThreshold() {
        DistanceThreshold=$('#DistanceThreshold').val();
        $('#Increasethreshold').click(function(){ 
            DistanceThreshold = Math.min(faceapi.utils.round(parseFloat(DistanceThreshold) + 0.01), 0.99)
            $('#DistanceThreshold').val(DistanceThreshold)
        });

        $('#Decreasethreshold').click(function(){
        DistanceThreshold = Math.max(faceapi.utils.round(parseFloat(DistanceThreshold) - 0.01), 0.1)
        $('#DistanceThreshold').val(DistanceThreshold)
        });  
    },
     /** @name 调整时间间距*/
    Decreasetime() {
        DistanceTime=$('#DistanceTime').val();
        $('#Increasetime').click(function(){ 
            DistanceTime = Math.min(faceapi.utils.round(parseFloat(DistanceTime) + 100), 6000)
            $('#DistanceTime').val(DistanceTime)
        });

        $('#Decreasetime').click(function(){
        DistanceTime = Math.max(faceapi.utils.round(parseFloat(DistanceTime) - 100), 300)
        $('#DistanceTime').val(DistanceTime)
        });  
    },
    /** @name 获取绘画参数 */
    getCheckbox(){
     var data=[];
     data['drawBoxes']=$("input[name='hideBoundingBoxes']:checked").val();
     data['withFaceLandmarks']=$("input[name='withFaceLandmarks']:checked").val();
     return data;
    },
    /** @name 运行 */
    async run() {
      
      ['#ssd_mobilenetv1_controls', '#tiny_face_detector_controls'].forEach(id => { $(id).hide(); });
        if(TINY_FACE_DETECTOR){
           $('#'+TINY_FACE_DETECTOR+'_controls').show() 
        }
      await facevideo.changeFaceDetector(this.models);
      await faceapi.loadFaceLandmarkModel(this.models);
      $('#scoreThreshold').val(this.matchedScore);
      await facevideo.ScoreThreshold();
      $('#minConfidence').val(this.matchedScore);
      $('#DistanceThreshold').val(this.threshold);
      await facevideo.DistanceThreshold();
      await facevideo.Decreasetime();
      await facevideo.playlist(0);
      
    },
    /*播放列表*/
    playlist(i){
       $('#videoid').val(i);
       this.video.src=this.videoUrl[i];
       $('#list'+(i+1)).addClass('active');
       this.video.load();
       if($("input[name='auto']:checked").val()){
            this.video.play();
       } 
       this.video.addEventListener('play', function () { //播放开始执行的函数
           document.querySelector('#playvideo').className='active';
           document.querySelector('#pausevideo').className=''; 
       });
      
    },
    /*列表自动播放*/
    autoplaylist(i){
       var x = document.querySelector('#video').ended;
       if(x==true){
            i=parseInt(i)+1;
            if(i>this.videoUrl.length-1){i=0;}
           this.video.src=this.videoUrl[i];
           $('#list'+(i+1)).addClass('active');
           this.video.load();
           this.video.play();
           $('#videoid').val(i);
           document.querySelector('#playvideo').className='active';
           document.querySelector('#pausevideo').className='';
       }else{
           return;
       }      
    },
    /*事件绑定*/
    bindEvents() {
        // "播放" 按钮
        this.playvideo.onclick = () => {
           this.video.play();
           this.playvideo.className='active';
           this.pausevideo.className='';
        };
        // "开始验证" 按钮
        this.pausevideo.onclick = () => {
          this.video.pause();
          this.pausevideo.className='active';
          this.playvideo.className='';
        };
        //检测
        this.startcheck.onclick = () => {
          check=true;
          facevideo.startVideo(this.video);
          if($("input[name='checkfaceimg']:checked").val()){
                facevideo.checkVideo(this.video);
          }
             
          this.startcheck.className='active';
          this.stopcheck.className='';
        };
        //停止
        this.stopcheck.onclick = () => {
           check=false;
           this.startcheck.className='';
           this.stopcheck.className='active';
        };
    },
    /** @name 更新时间 */
    updateTimeStats(timeInMs) {
        forwardTimes = [timeInMs].concat(forwardTimes).slice(0, 30)
        const avgTimeInMs = forwardTimes.reduce((total, t) => total + t) / forwardTimes.length
        $('#time').val(`${Math.round(avgTimeInMs)} ms`)
        $('#fps').val(`${faceapi.utils.round(1000 / avgTimeInMs)}`)
    },

    /** @name 对比人脸结果 */
    updateResult(image) {
        const distance = faceapi.utils.round(
        faceapi.euclideanDistance(descriptors.desc1, descriptors.desc2)
        )
        if (distance < $('#DistanceThreshold').val()) {
            const imgs=document.createElement("img");
            imgs.setAttribute("src", image.src);
            imgs.setAttribute("style", "width:106px;");
            document.getElementById('imgdiv').appendChild(imgs);
            console.log(distance,'同一人');
        }else{
            console.log(distance,'不是同一人'); 
        }
      
    },
    /** @name 上传图片 */
    preview(file,compress=false,width=150){
        var img = document.getElementById('img');
        if(file.files && file.files[0]) {
            if(compress){
            imgtemp=facevideo.compress(event, function(base64Img){
               img.src=base64Img;
            })
            }else{
               var reader = new FileReader();
                reader.onload = function(evt) {
                img.src = evt.target.result;
                img.src = imgtemp; 
               } 
               reader.readAsDataURL(file.files[0]); 
            }  
          } else {
                 layer.alert(file.value);
          }
    },
    /** @name 压缩图片 */
    compress(event, callback) {
        if ( typeof (FileReader) === 'undefined') {
            console.log("当前浏览器内核不支持base64图标压缩");
        //调用上传方式  不压缩
        } else {
            try {
                var file = event.currentTarget.files[0];
                    if(!/image\/\w+/.test(file.type)){   
                        alert("请确保文件为图像类型");  
                        return false;  
                    } 
                var reader = new FileReader();
                reader.onload = function (e) {
                var image = $('<img/>');
                image.load(function () {
                //console.log("开始压缩");
                var square = 150;
                var canvas = document.createElement('canvas');
                canvas.width = square;
                canvas.height = square;
                var context = canvas.getContext('2d');
                context.clearRect(0, 0, square, square);
                var imageWidth;
                var imageHeight;
                var offsetX = 0;
                var offsetY = 0;
                if (this.width > this.height) {
                    imageWidth = Math.round(square * this.width / this.height);
                    imageHeight = square;
                    offsetX = - Math.round((imageWidth - square) / 2);
                } else {
                    imageHeight = Math.round(square * this.height / this.width);
                    imageWidth = square;
                    offsetY = - Math.round((imageHeight - square) / 2);
                }
                context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                var data = canvas.toDataURL('image/jpeg');
                    //压缩完成执行回调
                    callback(data);
                });
                image.attr('src', e.target.result);
                };
                reader.readAsDataURL(file);
            } catch(e) {
                console.log("压缩失败!");
                //调用上传方式  不压缩
            }
        }
    }
}

exports('facevideo', facevideo);
});

